package org.tradesystem.tickernews;
import java.net.URL;
import java.util.Calendar;

import org.activequant.core.domainmodel.SeriesSpecification;
import org.activequant.core.domainmodel.data.TickerNews;
import org.activequant.core.domainmodel.data.TickerNewsSeries;
import org.activequant.core.types.TimeStamp;
import org.activequant.data.annotations.Vendor;
import org.activequant.data.retrieval.ITickerNewsSeriesSource;
import org.apache.log4j.Logger;
import org.encog.bot.rss.RSS;
import org.encog.bot.rss.RSSItem;

/**
* 
* abstracted Yahoo RSS TickerNews series source, gets all available news for a ticker symbol<br>
* RSSTickerNewsSeriesSource implements ITickerNewsSeriesSource. Holds the following associated variable:
* <ul>
* <li>rss(RSS)</li>
* </ul>
*/
@Vendor("Yahoo")
public class RSSTickerNewsSeriesSource implements ITickerNewsSeriesSource {
	/**
	 * private RSS rss;
	 */
	private RSS rss;

	protected final static Logger log = Logger.getLogger(RSSTickerNewsSeriesSource.class);
	/**
	 * constructs an RSSTickerNewsSeriesSource(implements ITickerNewsSeriesSource)
	 */
	public RSSTickerNewsSeriesSource() {
		
	}

	/**
	 * returns a TickerNewsSeries for the given query(SeriesSpecification) (by fetching historical data from Yahoo)
	 */
	public TickerNewsSeries fetch(SeriesSpecification query) throws Exception {
		rss = new RSS();
		if(query.getTimeFrame() == null) {
			throw new NullPointerException("timeFrame");
		}

		TimeStamp startDate = query.getStartTimeStamp();
		TimeStamp endDate = query.getEndTimeStamp();
		
		if(endDate == null) {
			log.warn("end date not specified: assuming now");
			endDate = new TimeStamp();
		}
		
		if(startDate == null) {
			log.warn("start date not specified: assuming 1 day before end");
			Calendar cal = Calendar.getInstance();
			cal.setTime(endDate.getDate());
			cal.add(Calendar.DAY_OF_YEAR, -1);
			startDate = new TimeStamp(cal.getTime());
		}
		
		String symbol=query.getInstrumentSpecification().getSymbol().toString();
		TickerNewsSeries tickerNewsSeries = new TickerNewsSeries(query);
		URL url = new URL("http://finance.yahoo.com/rss/headline?s="+symbol.toLowerCase());
	    rss.load(url,15000);
	    for(RSSItem item : rss.getItems()){
	    	TickerNews tickerNews=new TickerNews(query.getInstrumentSpecification());
	    	tickerNews.setTitle(item.getTitle());
	    	TimeStamp timeStamp=new TimeStamp(item.getDate());
	    	tickerNews.setTimeStamp(timeStamp);
	    	tickerNews.setLink(item.getLink());
	    	tickerNews.setDescription(item.getDescription());
	    	tickerNewsSeries.add(0, tickerNews);
	    }
	    return tickerNewsSeries;
	}
}
